package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.SystemDictionary;
import cn.wolfcode.crm.domain.SystemDictionaryItem;
import cn.wolfcode.crm.query.SystemDictionaryItemQueryObject;
import cn.wolfcode.crm.service.ISystemDictionaryItemService;
import cn.wolfcode.crm.service.ISystemDictionaryService;
import cn.wolfcode.crm.util.JsonResult;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/systemDictionaryItem")
public class SystemDictionaryItemController {

    @Autowired
    private ISystemDictionaryItemService systemDictionaryItemService;

    @Autowired
    private ISystemDictionaryService systemDictionaryService;


    @RequestMapping("/list")
    @RequiresPermissions(value = {"字典明细列表权限", "dept:list"}, logical = Logical.OR)
    public String list(@ModelAttribute("qo") SystemDictionaryItemQueryObject qo, Model model) {
        if (qo.getParentId() >=0) {
            PageInfo<SystemDictionaryItem> pageInfo = systemDictionaryItemService.selectByQo(qo);
            model.addAttribute("pageInfo", pageInfo);

        }
        //根据目录的id查
            model.addAttribute("dic",systemDictionaryService.selectById(qo.getParentId()));

        //查询字典目录信息 并存入域对象中
            List<SystemDictionary> systemDictionaries = systemDictionaryService.selectAll();
            model.addAttribute("dics", systemDictionaries);


        return "systemDictionaryItem/list";
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    @RequiresPermissions(value = {"字典明细编辑或新增权限", "dept:saveOrUpdate"}, logical = Logical.OR)
    public JsonResult saveOrUpdate(SystemDictionaryItem systemDictionaryItem, Model model) {
        JsonResult result = new JsonResult();
        try {
            systemDictionaryItemService.saveOrUpdate(systemDictionaryItem);
            //保存成功
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.mark("保存失败");
        }
        return result;
    }

    @RequestMapping("/delete")
    @ResponseBody
    @RequiresPermissions(value = {"字典明细删除权限", "dept:delete"}, logical = Logical.OR)
    public JsonResult delete(Long deptId) {
        JsonResult result = new JsonResult();
        try {
            if (deptId != null) {
                systemDictionaryItemService.deleteBydeptId(deptId);
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.mark("删除操作失败,请重试");
        }
        return result;
    }
}
